package com.cljh.mtmall.product.service.impl;

import com.cljh.mtmall.product.service.CategoryBrandRelationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cljh.common.utils.PageUtils;
import com.cljh.common.utils.Query;

import com.cljh.mtmall.product.dao.CategoryDao;
import com.cljh.mtmall.product.entity.CategoryEntity;
import com.cljh.mtmall.product.service.CategoryService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {
//    @Autowired
//    CategoryDao categoryDao;


    @Autowired
    private CategoryBrandRelationService categoryBrandRelationService;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> listWithTree() {
        //1.查出所有分类
//        List<CategoryEntity> categoryEntities = categoryDao.selectList(null);
        List<CategoryEntity> entities = baseMapper.selectList(null);
        //2.组装父子的树形结构
        //2.1查询所有的一级分类
        List<CategoryEntity> collect = entities.stream().filter((categoryEntity) ->
                //id为0的为父级
                categoryEntity.getParentCid() == 0
        ).peek((menu)->{
            //获取该父级的子集
            menu.setChildren(getChildren(menu,entities));
        }).sorted(
                //排序
                Comparator.comparingInt(menu -> (menu.getSort() == null ? 0 : menu.getSort()))
        ).collect(Collectors.toList());


        return collect;
    }

    @Override
    public boolean removeMenuByIds(List<Long> asList) {
        //TODO 1、检查当前删除的菜单，是否被其他地方引用

        //逻辑删除
        baseMapper.deleteBatchIds(asList);
        return false;
    }


    /**
     * 找到catelog的完整路径
     * [父路径/子路径]
     * @param catelogId
     * @return
     */
    @Override
    public Long[] findCatelogPath(Long catelogId) {
        List<Long> list = new ArrayList<>();
        List<Long> parentPath = findParentPath(catelogId, list);
        //逆序
        Collections.reverse(parentPath);


        return  list.toArray(new Long[parentPath.toArray().length]);
    }

    /**
     *级联更新所有关联的数据
     * @param category
     */
    @Transactional
    @Override
    public void updateDetail(CategoryEntity category) {
        this.updateById(category);
        if (!StringUtils.isEmpty(category.getName())){
            categoryBrandRelationService.updateCategory(category.getCatId(),category.getName());
        }
    }

    private List<Long> findParentPath(Long catelogId,List<Long> paths){
        //1.收集当前节点id
        paths.add(catelogId);
        CategoryEntity byId = this.getById(catelogId);
        if (byId.getParentCid()!=0){
            findParentPath(byId.getParentCid(),paths);
        }
        return paths;
    }


    //递归查找
    private List<CategoryEntity> getChildren(CategoryEntity root,List<CategoryEntity> all){
        List<CategoryEntity> collect = all.stream()
                .filter(category -> Objects.equals(category.getParentCid(), root.getCatId()))
                //找到子菜单递归查询
                .peek(category -> category.setChildren(getChildren(category,all)))
                //排序
                .sorted(Comparator.comparingInt(menu -> (menu.getSort() == null ? 0 : menu.getSort())))
                .collect(Collectors.toList());
        return collect;
    }
}